package com.commonClass.set;

import java.util.HashMap;

public class TestHashMap {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        //添加键值对,put关键字
        hashMap.put(1,"hello");//数字:字符串
        hashMap.put(2,"you");
        hashMap.put(3,"are");
        hashMap.put(4,"my");
        hashMap.put(5,"friend");
        hashMap.put(6,null);
        System.out.println(hashMap);//HashMap重写了toString 方法{1=hello, 2=you, 3=are, 4=my, 5=friend, 6=null}
        hashMap.put("seven","hahaha");//字符串:字符串
        System.out.println(hashMap);//{1=hello, 2=you, 3=are, 4=my, 5=friend, 6=null, seven=hahaha}
        hashMap.put(null,"test");
        System.out.println(hashMap);//{null=test, 1=hello, 2=you, 3=are, 4=my, 5=friend, 6=null, seven=hahaha}
        hashMap.put(null,"emm");//把之前的test覆盖了
        System.out.println(hashMap);//{null=emm, 1=hello, 2=you, 3=are, 4=my, 5=friend, 6=null, seven=hahaha}

        //访问元素 get(key)得到value
        System.out.println(hashMap.get(null));//emm
        System.out.println(hashMap.get(3));//are
        System.out.println(hashMap.get("seven"));//hahaha

        //删除元素 remove(key) 删除键值对
        hashMap.remove(null);
        System.out.println(hashMap);//{1=hello, 2=you, 3=are, 4=my, 5=friend, 6=null, seven=hahaha}
        //删除所有 clear()
        hashMap.clear();
        System.out.println(hashMap);//{}

        //遍历hashMap
        HashMap<Integer,String> hashMap2 = new HashMap<Integer,String>();
        hashMap2.put(1,"hello");//数字:字符串
        hashMap2.put(2,"you");
        hashMap2.put(3,"are");
        hashMap2.put(4,"my");
        hashMap2.put(5,"friend");
        hashMap2.put(6,null);
        // 输出 key 和 value
        for (Integer i : hashMap2.keySet()) {
            System.out.println("key: " + i + " value: " + hashMap2.get(i));
            /*
            key: 1 value: hello
            key: 2 value: you
            key: 3 value: are
            key: 4 value: my
            key: 5 value: friend
            key: 6 value: null
            */
        }
        // 返回所有 value 值
        for(String value: hashMap2.values()) {
            // 输出每一个value
            System.out.print(value + ", ");
            //hello, you, are, my, friend, null,
        }
    }
}

    